package cdu.xjj.aop;


import cdu.xjj.controller.DeptController;
import cdu.xjj.mapper.OperateLogMapper;
import cdu.xjj.pojo.OperateLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

//@Slf4j
@Component
@Aspect
public class OperationLogAspect {
    //注入mapper
    @Autowired
    private OperateLogMapper operateLogMapper;

    private static final Logger log= LoggerFactory.getLogger(DeptController.class);

    //切面方法
     @Around("@annotation(cdu.xjj.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint)  throws Throwable {
          // 记录开始运行时间
          long startTime = System.currentTimeMillis();
          // 执行目标方法
          Object result = joinPoint.proceed();
          // 记录结束运行时间
          long endTime = System.currentTimeMillis();
          // 计算耗时
          long costTime = endTime - startTime;

          // 获取方法签名
          MethodSignature signature = (MethodSignature) joinPoint.getSignature();
          Method method = signature.getMethod();

          OperateLog olog= new OperateLog();
           olog.setOperateEmpId(getCurrentUserId());
           olog.setOperateTime(LocalDateTime.now());
           olog.setClassName(joinPoint.getTarget().getClass().getName());
           olog.setMethodName(joinPoint. getSignature().getName());
           olog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
           olog.setReturnValue(result!= null ? result.toString() : "null");
           olog.setCostTime(costTime);

           //保存日志
           log.info("记录操作日志：{}",log);

           operateLogMapper.insert(olog);

           return result;
    }

    private Integer getCurrentUserId() {
        return 1;
    }
}
